#lang racket


(require "global.rkt"
         (prefix-in backends: "backends/main.rkt")
         (prefix-in ac: "autocad/main.rkt")
         (prefix-in rh: "rhinoceros3d/main.rkt"))

(provide (all-from-out "autocad/main.rkt"
                       "rhinoceros3d/main.rkt"))

(provide autocad
         rhino
         backend
         load-null-backend)


(define backend-cache (make-hasheq))

(define (add-backend-cache! backend% backend)
  (hash-set! backend-cache backend% backend))

(define (member-backend-cache? backend%)
  (hash-has-key? backend-cache backend%))

(define (get-backend-cache backend%)
  (hash-ref backend-cache backend%))


(define autocad ac:autocad-backend%)
(define rhino rh:rhino-backend%)


(define (ensure-backend backend%)
  (cond ((member-backend-cache? backend%)
         (get-backend-cache backend%))
        (else
         (let ((backend (new backend%)))
           (add-backend-cache! backend% backend)
           backend))))

(define (initialize-backend backend sym)
  (when (eq? sym 'delete)
    (send backend delete-shapes)))


(define (backend backend% (sym #f))
  (let ((backend (ensure-backend backend%)))
    (set-current-in-backend! backend)
    (set-current-out-backend! backend)
    (initialize-backend backend sym)
    backend))

(define (load-null-backend)
  (backend backends:null-backend%))